package org.tigris.atlas.quizme.client.action;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.tigris.atlas.quizme.client.utils.Constants;
import org.tigris.atlas.quizme.transfer.Answer;
import org.tigris.atlas.quizme.transfer.Question;

/**
 * Run after every time the user submits an answer.
 * 
 * @author Robert Simmering
 */
public class SelectAnswerAction  extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
		      HttpServletRequest request, HttpServletResponse response) {	
		String sIndex = request.getParameter("index");
		
		int index = Integer.parseInt(sIndex);
		List userAnswers = (List)request.getSession().getAttribute(Constants.ANSWERS_KEY);
		List questions = (List)request.getSession().getAttribute(Constants.QUESTIONS_KEY);
		request.setAttribute("SelectedAnswer",userAnswers.get(index));
		Question question = (Question)questions.get(index);
		request.setAttribute(Constants.CURRENT_QUESTION_KEY,question);
		request.setAttribute(Constants.QUESTION_INDEX_KEY,""+index);
		
		Collection answers = question.getAnswers();
		
		List<Answer> list = new ArrayList<Answer>(answers.size());
		list.addAll(answers);
		//	Sort answers groups according to order
		Collections.sort(list, new Comparator<Answer>() {
		    public int compare(Answer a1, Answer a2) {
		    	if(a1.getOrder() == null){
		    		return 0;
		    	}
		        return a1.getOrder().compareTo(a2.getOrder());
	    }});
		
		 request.getSession().setAttribute(Constants.CURRENT_ANSWERS_KEY, list);
		 
		return mapping.findForward("success");
	}
}